const Upload = require('../models/upload.model');
var multer  = require('multer')
var path=require('path');
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './uploads')
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
  }
})

exports.upload = function(req, res, next) {
  
  var upload = multer({ storage: storage }).single('avatar');
  upload(req,res,function(err){
     //console.log(req.file)
     //console.log(req.body)
   console.log(new Date().toLocaleDateString())
   console.log(req.file)
   console.log(err)
    req.file['date']=new Date().toLocaleDateString();
    req.file['belong']=req.body.belong
    const upload = new Upload(req.file);
    

    upload.save().then(data => {
    res.json(data);
    
  });
  })
};
// 新
exports.create = function(req, res, next) {
  const upload = new Upload(req.body);
  upload.save().then(data => {
    res.json(data);
  });
};
// 删
exports.remove = function(req, res, next) {
  var id = req.params.id;
  Upload.findByIdAndDelete(id, (err, data) => {
    res.json(data);
  });
};

exports.removes = function(req, res, next) {
  var ids = req.body.ids.split(',');
  Upload.remove({ _id: { $in: ids } }).then(data => {
    res.json({ message: '数据删除成功', status: 200 });
  });
};
// 改
exports.update = function(req, res, next) {
  var id = req.params.id;
  Upload.findByIdAndUpdate(id, { $set: req.body }, { new: false }).then(data => {
    // 千万小心，这里的data是没有更新之前的数据
    res.json(data);
  });
};

exports.getData = function(req, res, next) {
  var id = req.params.id;
  Upload.findById(id).then(data => {
    res.json(data);
  });
};

//查
exports.list = function(req, res, next) {
  // page
  // limit
  var page = req.body.page ? req.body.page : 1;
  var rows = req.body.rows ? req.body.rows : 10;
  
   var queryCondition = {};
console.log(req.body.name)
  if (req.body.name) {
    
    name = req.body.name;
    queryCondition ['originalname']=  new RegExp(name, 'i');

  }
  if (req.body.belong && req.body.belong.trim().length > 0) {
    belong = req.body.belong;
    queryCondition['belong']= new RegExp(belong,'i')
  }

  Upload.paginate(queryCondition, { page: +page, limit: +rows }, function(err, result) {
    result.rows = result.docs;
    delete result.docs;
    console.log(result.rows)
    res.json(result);
  });
};
